﻿using ConfExpert.Forms.Araclar;
using ConfExpert.Utility;
using ConfExpert.Utility.Grid;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.Customization;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraVerticalGrid.Rows;
using DevTeamIT;
using Extensions;
using ITaskManager.Datasets;
using ITaskManager.Datasets.MyDataTableAdapters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Base
{

    public partial class XForm : DevForm
    {
        public bool ytk(int x)
        {
            return Session.ytk(x);
        }

        public int ChangesSubmitted = 0;
        public TableAdapterManager TAM;
        public ITaskManager.Datasets.MyData ds;

        public void RefreshLookups()
        {
            AppSession.MainForm.RefreshData();
        }

        public Image notready = ITaskManager.Properties.Resources.kumasyok4;  //notready5;

        public bool isProd
        {
            get
            {
                return Session.DatabaseName == "PRODUCTION";
            }
        }

        public bool isKD
        {
            get
            {
                return Session.MyDept == 7 || Session.WhoAmI == 4;
            }
        }

        public bool isTL
        {
            get
            {
                return RepositoryManager.dsi.V_User.Select("TeamLeaderId=" + Session.WhoAmI.ToStr()).Length > 0;
            }
        }

        public bool isMP
        {
            get
            {
                return Session.MyDept == 11;
            }
        }

        public XForm()
        {
            InitializeComponent();

            ds = new ITaskManager.Datasets.MyData();

            ds.EnforceConstraints = false;

            foreach (DataRelation rel in ds.Relations)
            {
                //if (rel.ChildTable.Constraints.Count > 0)
                //    for (int i = 0; i < rel.ChildTable.Constraints.Count; i++)
                //    {
                //        Constraint con = rel.ChildTable.Constraints[i];
                //        if (con is ForeignKeyConstraint)
                //            rel.ChildTable.Constraints.Remove(con);
                //    }

                ForeignKeyConstraint ParentFK = new ForeignKeyConstraint(rel.ParentColumns, rel.ChildColumns);
                ParentFK.UpdateRule = Rule.Cascade;
                rel.ChildTable.Constraints.Add(ParentFK);
            }
            TAM = new TableAdapterManager();
        }


        public RepositoryItemCheckedComboBoxEdit riGenel = new RepositoryItemCheckedComboBoxEdit();
        private void XForm_Load(object sender, EventArgs e)
        {
            foreach (DataRow dr in RepositoryManager.dsi.stGenel)
                riGenel.Items.Add(dr["Name"].ToString(), CheckState.Unchecked);

            this.FormClosing += XForm_FormClosing;
        }

        public void vgc_CustomDrawRowHeaderCell(object sender, DevExpress.XtraVerticalGrid.Events.CustomDrawRowHeaderCellEventArgs e)
        {
            if (!(e.Row is CategoryRow))
            {
                //e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
                e.Appearance.BackColor = Color.LightBlue;    // SystemColors.Info;
                //e.Appearance.ForeColor = Color.DimGray;   // DarkOliveGreen;    // SystemColors.Info;
                //e.Handled = true;
            }
        }

        public virtual void Save()
        {
            EndEdits();



            /*
            try
            {
                db.SubmitChanges(ConflictMode.ContinueOnConflict);
            }

            catch (ChangeConflictException e)
            {
                Console.WriteLine(e.Message);
                // Automerge database values for members that client 
                // has not modified. 
                foreach (ObjectChangeConflict occ in db.ChangeConflicts)
                {
                    occ.Resolve(RefreshMode.KeepChanges);
                }
            }

            // Submit succeeds on second try.
            db.SubmitChanges(ConflictMode.FailOnFirstConflict);
            */



            try
            {
                this.Cursor = Cursors.WaitCursor;
                Notify("Saving...");

                if (ds.HasChanges())
                    ChangesSubmitted += TAM.UpdateAll(ds);
            }
            catch (DBConcurrencyException ex)
            {
                using (ConcurrencySolver cs = new ConcurrencySolver(ex.Row))
                {
                    DialogResult response = System.Windows.Forms.DialogResult.OK;

                    if (cs.DialogResult != System.Windows.Forms.DialogResult.OK)
                        response = cs.ShowDialog();

                    if (response == System.Windows.Forms.DialogResult.OK)
                        GetDetails(ex.Row.Table.TableName, "UpdConfilict", cs.Sql);

                    switch (response)
                    {
                        case DialogResult.OK:
                            try
                            {
                                Save();
                            }
                            catch (Exception saveEx)
                            {
                                LogManager.LogToDB("Conc.Exc:" + saveEx.ToStr() + "-" + cs.Log + response.ToString());
                                throw saveEx;
                            }
                            //LogManager.LogToDB(cs.Log + response.ToString());
                            break;
                        case DialogResult.Cancel:
                            LogManager.LogToDB(cs.Log + response.ToString());
                            throw new ApplicationException("Değişiklikler KAYDEDİLMEDİ !!!");
                    }
                }

            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                this.Cursor = Cursors.Default;
                Notify(string.Empty);
            }
        }

        //public virtual void XForm_FormClosing(object sender, FormClosingEventArgs e)
        public void XForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //GC.Collect();
            AppSession.MainForm.SetActiveXFormFromMDIManager();
            ds.Dispose();
            //this.Dispose();
            //GC.Collect();
        }

        public void AksesuarAlanlariEkle(GridView gv)
        {
            //gv.GridControl.ForceInitialize();
            int idx = gv.Columns["AksesuarId"].VisibleIndex;
            MyAddField(gv, "BrandId", ref idx, RI(Rp.Brand));
            MyAddField(gv, "ProductCategoryId", ref idx, RI(Rp.ProductCategory));
            MyAddField(gv, "Renk", ref idx);
            MyAddField(gv, "Boy", ref idx);
            MyAddField(gv, "Etiket", ref idx);
            MyAddField(gv, "Aciklama", ref idx);
            MyAddField(gv, "AksSeriId", ref idx);
        }


        public List<CustomizationForm> CustomizationForms = new List<CustomizationForm>();
        public void ri_NewValue(object sender, ProcessNewValueEventArgs e)
        {
            string newEntry = e.DisplayValue.ToString();
            if (newEntry != string.Empty)
            {
                DataTable dt = (DataTable)((GridLookUpEdit)sender).Properties.DataSource;
                if (dt.Select(dt.Columns[0] + " = '" + newEntry + "'").Length == 0)
                    dt.Rows.Add(newEntry);

                e.Handled = true;
            }
        }

        void ri_QueryCheckStateByValue(object sender, DevExpress.XtraEditors.Controls.QueryCheckStateByValueEventArgs e)
        {
            if (e.Value == DBNull.Value)
            {
                e.CheckState = CheckState.Unchecked;
                e.Handled = true;
            }
        }

        #region Gridview Helpers
        public void InitGridView(GridView gridview, BindingSource bs)
        {
            //gridview.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.MouseDownFocused;            

            //System.Diagnostics.Debug.Listeners.Add(new  System.Diagnostics.TextWriterTraceListener(Console.Out));
            //System.Diagnostics.Debug.AutoFlush = true;
            //System.Diagnostics.Debug.Indent();

            try
            {
                gridview.GridControl.MenuManager = barManager;
                gridview.SelectionChanged -= gridview_SelectionChanged;
                gridview.SelectionChanged += gridview_SelectionChanged;
                //gridview.CustomDrawCell -= gridview_CustomDrawCell;
                //gridview.CustomDrawCell += gridview_CustomDrawCell;

                gridview.BeginUpdate();
                gridview.Columns.Clear();
                if (bs != null)
                {
                    gridview.GridControl.DataSource = null;
                    gridview.GridControl.DataSource = bs;
                    gridview.PopulateColumns();
                }

                //gridview.Appearance.HeaderPanel.Options.UseTextOptions = true;
                //gridview.Appearance.HeaderPanel.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                //gridview.ColumnPanelRowHeight = 40;

                bool containsProduct = gridview.Columns.Contains(gridview.Columns["ProductId"]);
                bool containsAksesuar = gridview.Columns.Contains(gridview.Columns["AksesuarId"]);
                bool containsStok = gridview.Columns.Contains(gridview.Columns["StokId"]);
                foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridview.Columns)
                {
                    switch (AppSession.Settings.AutoFilterCondition)
                    {
                        case "Contains": col.OptionsFilter.AutoFilterCondition = AutoFilterCondition.Contains; break;
                        case "StartsWith": col.OptionsFilter.AutoFilterCondition = AutoFilterCondition.Like; break;
                    }

                    //System.Diagnostics.Debug.WriteLine(col.FieldName);

                    if (col.FieldName != bs.DataMember + "Id")
                        MapGridColumn(col);
                    else
                    {
                        col.OptionsColumn.AllowEdit = false;
                        col.AppearanceCell.BackColor = System.Drawing.Color.LightYellow;
                    }

                    if (col.ColumnType == Type.GetType("System.Boolean"))
                    {
                        RepositoryItemCheckEdit ri = new RepositoryItemCheckEdit();
                        ri.NullStyle = StyleIndeterminate.Inactive;
                        ri.AllowGrayed = false;
                        ri.QueryCheckStateByValue -= ri_QueryCheckStateByValue;
                        ri.QueryCheckStateByValue += ri_QueryCheckStateByValue;     //burada olması doğru mu?
                        col.ColumnEdit = ri;
                    }
                    else if (col.ColumnType == typeof(DateTime))
                    {
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.DateSmart;
                        col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                        col.OptionsFilter.ImmediateUpdateAutoFilter = true;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnCheck = DevExpress.Utils.DefaultBoolean.True;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnDateChange = DevExpress.Utils.DefaultBoolean.True;
                        //col.DisplayFormat.FormatString = "dd.MM.yyyy HH:mm.ss";

                    }
                    else if (col.ColumnEdit is RepositoryItemGridLookUpEdit)
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.CheckedList;

                }
                if (containsStok)
                {
                    GridColumn colStokTipi = new GridColumn();
                    colStokTipi.FieldName = "StokTipi";
                    gridview.Columns.Add(colStokTipi);
                }
                if (containsProduct)
                {

                    GridColumn colPhoto = new GridColumn();
                    if (gridview.GetType() == typeof(DevExpress.XtraGrid.Views.BandedGrid.BandedGridView))
                        colPhoto = new DevExpress.XtraGrid.Views.BandedGrid.BandedGridColumn();

                    colPhoto.FieldName = "Scan";
                    gridview.Columns.Add(colPhoto);

                    colPhoto.ColumnEdit = new RepositoryItemPictureEdit();
                    colPhoto.UnboundType = DevExpress.Data.UnboundColumnType.Object;

                    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).SizeMode = PictureSizeMode.Clip;
                    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).NullText = " ";
                    CenterGridColumn(colPhoto);

                    gridview.RowCellClick -= new RowCellClickEventHandler(gridview_RowCellClick);
                    gridview.MouseMove -= new MouseEventHandler(gridview_MouseMove);

                    gridview.RowCellClick += new RowCellClickEventHandler(gridview_RowCellClick);
                    gridview.MouseMove += new MouseEventHandler(gridview_MouseMove);

                    List<string> visibleColumnNames = new List<string>();
                    foreach (GridColumn gc in gridview.Columns)
                        if (gc.Visible)
                            visibleColumnNames.Add(gc.FieldName);

                    foreach (GridColumn gc in gridview.Columns)
                        gc.VisibleIndex = -1;

                    int k = -1;
                    if (gridview.GetType() == typeof(BandedGridView))
                        k++;

                    if (visibleColumnNames.Contains("ProductId"))
                    {
                        int scanIndex = visibleColumnNames.IndexOf("ProductId");
                        visibleColumnNames.Insert(scanIndex, "Scan");
                    }
                    else if (gridview.Columns["Scan"] != null)
                        visibleColumnNames.Insert(0, "Scan");

                    foreach (string colName in visibleColumnNames)
                    {
                        GridColumn col = gridview.Columns[colName];
                        k++;
                        col.VisibleIndex = k;
                    }

                    gridview.CalcRowHeight -= new RowHeightEventHandler(gridview_CalcRowHeight);
                    gridview.CustomDrawCell -= new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(XForm_CustomDrawCell);
                    gridview.CalcRowHeight += new RowHeightEventHandler(gridview_CalcRowHeight);
                    gridview.CustomDrawCell += new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(XForm_CustomDrawCell);
                }
                else
                {
                    //if (containsAksesuar)
                    //{
                    //    if (
                    //       gridview.Name == "gvAksesuarAge" ||
                    //       gridview.Name == "gvAksResim" ||
                    //       gridview.Name == "gvAksStok" ||
                    //       gridview.Name == "gvPOLines" ||
                    //       gridview.Name == "gvIrsaliyeLines" ||
                    //       gridview.Name == "gvCikisPartisiLines" ||
                    //       gridview.Name == "gvTalepLines" ||
                    //       gridview.Name == "gvGirisPartisiLines" ||
                    //       gridview.Name == "gvTreeLines" ||
                    //       gridview.Name == "gvBedenEtiketleri" ||
                    //       gridview.Name == "gvMyTreeLines" ||
                    //       gridview.Name == "gvSayimAnaliz" ||
                    //       gridview.Name == "gvAksSayim" ||
                    //       gridview.Name == "gvAksPOSipLines"
                    //       )
                    //        AksesuarAlanlariEkle(gridview);


                    //    GridColumn colPhoto = new GridColumn();
                    //    if (gridview.GetType() == typeof(DevExpress.XtraGrid.Views.BandedGrid.BandedGridView))
                    //        colPhoto = new DevExpress.XtraGrid.Views.BandedGrid.BandedGridColumn();

                    //    colPhoto.FieldName = "ScA";
                    //    gridview.Columns.Add(colPhoto);

                    //    colPhoto.ColumnEdit = new RepositoryItemPictureEdit();
                    //    colPhoto.UnboundType = DevExpress.Data.UnboundColumnType.Object;

                    //    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).SizeMode = PictureSizeMode.Clip;
                    //    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).NullText = " ";
                    //    CenterGridColumn(colPhoto);

                    //    gridview.CustomUnboundColumnData -= new CustomColumnDataEventHandler(gvAks_CustomUnboundColumnData);
                    //    gridview.RowCellClick -= new RowCellClickEventHandler(gridview_RowCellClick);
                    //    gridview.MouseMove -= new MouseEventHandler(gridview_MouseMove);

                    //    gridview.CustomUnboundColumnData += new CustomColumnDataEventHandler(gvAks_CustomUnboundColumnData);
                    //    gridview.RowCellClick += new RowCellClickEventHandler(gridview_RowCellClick);
                    //    gridview.MouseMove += new MouseEventHandler(gridview_MouseMove);

                    //    Dictionary<string, int> visibleColumnNames = new Dictionary<string, int>();
                    //    foreach (GridColumn gc in gridview.Columns)
                    //        if (gc.Visible)
                    //            visibleColumnNames.Add(gc.FieldName, gc.VisibleIndex);

                    //    foreach (GridColumn gc in gridview.Columns)
                    //        gc.VisibleIndex = -1;

                    //    int k = -1;
                    //    if (gridview.GetType() == typeof(BandedGridView))
                    //        k++;

                    //    if (visibleColumnNames.ContainsKey("AksesuarId"))
                    //    {
                    //        int scanIndex = visibleColumnNames.FirstOrDefault(x => x.Key == "AksesuarId").Value.ToInt();
                    //        visibleColumnNames.Add("ScA", scanIndex);
                    //    }
                    //    else if (gridview.Columns["ScA"] != null)
                    //        visibleColumnNames.Add("ScA", 0);

                    //    foreach (KeyValuePair<string, int> colName in visibleColumnNames)
                    //    {
                    //        int visibleIndex = k == -1 ? colName.Value : colName.Value + 1;
                    //        GridColumn col = gridview.Columns[colName.Key];
                    //        col.VisibleIndex = visibleIndex;
                    //    }

                    //    gridview.CalcRowHeight -= new RowHeightEventHandler(gridview_CalcRowHeight);
                    //    gridview.CustomDrawCell -= new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(XForm_CustomDrawCell);
                    //    gridview.CalcRowHeight += new RowHeightEventHandler(gridview_CalcRowHeight);
                    //    gridview.CustomDrawCell += new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(XForm_CustomDrawCell);
                    //}
                }


                //gridview.OptionsView.ShowViewCaption = true;
                gridview.BestFitMaxRowCount = 50;
                gridview.GridControl.ShowOnlyPredefinedDetails = true;
                gridview.HorzScrollStep = 50;
                gridview.NewItemRowText = "Yeni kayıt girmek için tıklayınız.";
                gridview.OptionsBehavior.CopyToClipboardWithColumnHeaders = false;
                gridview.OptionsBehavior.EditorShowMode = AppSession.Settings.EditorShowMode;   // DevExpress.Utils.EditorShowMode.MouseUp;   //checkbox hemen seçilebilsin diye!                
                gridview.OptionsBehavior.ImmediateUpdateRowPosition = false;
                gridview.OptionsBehavior.KeepFocusedRowOnUpdate = true;
                gridview.OptionsFilter.AllowColumnMRUFilterList = true;
                gridview.OptionsFilter.ShowAllTableValuesInCheckedFilterPopup = false;
                gridview.OptionsFilter.ShowAllTableValuesInFilterPopup = false;
                gridview.OptionsFind.HighlightFindResults = true;
                gridview.OptionsHint.ShowColumnHeaderHints = true;
                gridview.OptionsMenu.EnableColumnMenu = true;
                gridview.OptionsMenu.ShowDateTimeGroupIntervalItems = true;
                gridview.OptionsNavigation.UseOfficePageNavigation = true;
                gridview.OptionsSelection.MultiSelect = true;
                gridview.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
                gridview.OptionsView.ColumnAutoWidth = false;
                //gridview.OptionsView.EnableAppearanceEvenRow = true;
                gridview.OptionsView.EnableAppearanceOddRow = true;    // Session.SettingsEnableAppearanceEvenRow;
                gridview.OptionsView.RowAutoHeight = true;
                gridview.OptionsView.ShowAutoFilterRow = true;
                gridview.OptionsView.ShowDetailButtons = false;
                gridview.OptionsView.ShowGroupPanel = false;
                gridview.ViewCaption = gridview.ViewCaption.Replace("gv", string.Empty);
                gridview.OptionsMenu.ShowConditionalFormattingItem = true;
                gridview.OptionsMenu.ShowAddNewSummaryItem = DevExpress.Utils.DefaultBoolean.True;



                //gridview.OptionsSelection.EnableRowHotTrack;

                //Set the caption to null, put the caption text in the TitlePanel and ShowTitlePanel!

                //gridview.GridControl.ShowOnlyPredefinedDetails = true;                

                //gridview.ShownEditor += new EventHandler(GridView_ShownEditor);
                //gridview.HiddenEditor+=new EventHandler(GridView_HiddenEditor);


                foreach (GridColumn gc in gridview.Columns)
                {
                    string colName = gc.FieldName.ToLower();
                    if (colName == "modifiedon" || colName == "ts" || colName == "deleted")
                        gc.Visible = false;
                    else
                        gc.Visible = true;
                }


                GridManager.GetManager(gridview);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                gridview.EndUpdate();
            }
        }




        public void MapGridColumn(GridColumn col)
        {
            string fieldName = col.FieldName.ToLower();

            col.FilterMode = ColumnFilterMode.DisplayText;
            col.OptionsFilter.AutoFilterCondition = AppSession.Settings.AutoFilterCondition == "Contains" ? AutoFilterCondition.Contains : AutoFilterCondition.Like;
            col.OptionsColumn.AllowEdit = col.FieldName != "UserId";    //userId sonradan değiştirilemesin diye!

            RepositoryItem ri = GetFieldRI(fieldName);
            if (ri != null)
            {
                col.ColumnEdit = ri;

                string F = fieldName.Replace("Id".ToLower(), string.Empty);
                if (Session.LookupDict.ContainsKey(F))
                    if (Session.LookupDict[F].Caption != string.Empty)
                        col.Caption = Session.LookupDict[F].Caption;

                //TODO: önce GetDeletions'ı dolduralım, sonra da CustomDisplayText ile silinmiş öğeleri grid'e getirelim!
                //ri.CustomDisplayText -= ri_CustomDisplayText;
                //ri.CustomDisplayText += ri_CustomDisplayText;
            }
            else if (col.ColumnType == typeof(String))
                col.ColumnEdit = new RepositoryItemTextEdit();

            switch (fieldName)
            {
                case "photo":
                case "photo0":
                case "photo1":
                case "photo2":
                case "photo3":
                case "photomikro":
                case "photolarge":
                    CenterGridColumn(col);
                    break;

                case "deleted":
                case "temp":
                case "ınsertedon":
                case "modifiedon":
                case "ts": col.Visible = false; break;

                case "en": _FormatAsNumeric(col); break;

                default:
                    if (fieldName.IndexOf("qty") > -1 || ";bol;kalan;ordermt;gelenmt;beklenenmt;yuklenenmt;metre;adet;eksik;alt;ust;fark;gelenmetre;cikanmetre;toplam;toplamyuklenenmt;toplammt;toplamfark;siparisedilenmt;toplamsiparismiktar;toplamsipmiktari;toplamgelenmiktar;yuklenengelenmiktar;ayrimmt;mt;yuklenenmt;depoyagelenmt;otherquantities;reorderpoint;percentage;metraj;en;point;".Contains(";" + fieldName + ";"))
                        _FormatAsNumeric(col);
                    else if (";fiyat;hedeffiyat;anlasilanfiyat;xanlasilanfiyat;faturafiyati;xfaturafiyati;birimfiyat;unitprice;latestunitprice;price;price_;cost;balance;linetotal;subtotal;discount;grandtotal;taxamt;freight;".Contains(";" + fieldName + ";"))
                        _FormatAsNumeric2(col);

                    break;
            }

        }

        void ri_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
        {
            //int dummy = RepositoryManager.GetIndexOf((RepositoryItemGridLookUpEdit)sender);
            //if (dummy > 0)
            //{
            //    MyData.DeletionsRow r = RepositoryManager.dsi.Deletions.FindByLookUpIdVal(dummy, e.Value.ToInt());
            //    if (r != null)
            //        e.DisplayText = r.Name;
            //}


            RepositoryItemGridLookUpEdit ritem = sender as RepositoryItemGridLookUpEdit;
            if (ritem == null)
                ritem = (sender as GridLookUpEdit).Properties;
            if (e.DisplayText == string.Empty)
            {
                int index = RepositoryManager.GetIndexOf((RepositoryItemGridLookUpEdit)sender);
                if (index > 0)
                {
                    MyData.DeletionsRow r = RepositoryManager.dsi.Deletions.FindByLookUpIdVal(index, e.Value.ToInt());
                    if (r != null)
                        e.DisplayText = r.Name;
                }

                //e.DisplayText = tableDeleted.Rows.OfType<DataRow>().Where(r => r[ritem.ValueMember].Equals(e.Value)).FirstOrDefault()[ritem.DisplayMember].ToString();
            }
        }


        public RepositoryItem GetFieldRI(string fieldName)
        {
            fieldName = fieldName.ToLower();

            if (fieldName.EndsWith("Id".ToLower()))
            {
                fieldName = fieldName.Substring(0, fieldName.Length - 2)
                                     .Replace("latest", "")
                                     .Replace("prf", "");

                if (Session.LookupDict.ContainsKey(fieldName))
                    return RI(Session.LookupDict[fieldName].LookupId);
                else
                    return null;
            }
            else
            {
                switch (fieldName)
                {
                    case "photomikro":
                        return RepositoryManager.GetPhotoRI();

                    default:
                        if (fieldName.IndexOf("qty") > -1 || ";bol;kalan;ordermt;gelenmt;beklenenmt;yuklenenmt;metre;adet;eksik;alt;ust;fark;gelenmetre;cikanmetre;toplam;toplamyuklenenmt;toplammt;toplamfark;siparisedilenmt;toplamsiparismiktar;toplamsipmiktari;toplamgelenmiktar;yuklenengelenmiktar;ayrimmt;mt;yuklenenmt;depoyagelenmt;otherquantities;reorderpoint;percentage;metraj;en;point;".Contains(";" + fieldName + ";"))
                            return new RepositoryItemCalcEdit();

                        return null;
                }
            }
        }

        public void InitLayoutView(DevExpress.XtraGrid.Views.Layout.LayoutView layoutview, BindingSource bs)
        {
            try
            {
                layoutview.BeginUpdate();

                if (bs != null)
                    layoutview.GridControl.DataSource = bs;

                foreach (DevExpress.XtraGrid.Columns.GridColumn col in layoutview.Columns)
                    if (col.FieldName != this.Name + "Id")
                        MapGridColumn(col);

                layoutview.EndUpdate();
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }

        }


        public void AddInlineDetailGrid(GridView gvMaster, GridView gvDetail, string KeyColumn, string Caption, DataSet dsSource, int ParentTableIndex, int ChildTableIndex)
        {
            DataColumn keyColumn = dsSource.Tables[ParentTableIndex].Columns[KeyColumn];
            DataColumn foreignKeyColumn = dsSource.Tables[ChildTableIndex].Columns[KeyColumn];
            dsSource.Relations.Add(Caption, keyColumn, foreignKeyColumn);

            gvMaster.GridControl.LevelTree.Nodes.Add(Caption, gvDetail);
            gvMaster.OptionsView.ShowDetailButtons = true;

            gvDetail.PopulateColumns(dsSource.Tables[ChildTableIndex]);

            gvDetail.OptionsBehavior.CopyToClipboardWithColumnHeaders = false;

            gvDetail.SelectionChanged -= gridview_SelectionChanged;
            gvDetail.SelectionChanged += gridview_SelectionChanged;

            foreach (DevExpress.XtraGrid.Columns.GridColumn col in gvDetail.Columns)
                MapGridColumn(col);

            gvDetail.OptionsNavigation.UseOfficePageNavigation = true;
            gvDetail.OptionsSelection.MultiSelect = true;
            gvDetail.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
            gvDetail.OptionsView.ColumnAutoWidth = false;
            gvDetail.OptionsView.ShowAutoFilterRow = true;
            gvDetail.OptionsView.ShowDetailButtons = false;
            gvDetail.OptionsView.ShowGroupPanel = false;
            gvDetail.BestFitMaxRowCount = 50;
            gvDetail.BestFitColumns();

            foreach (GridColumn gc in gvDetail.Columns)
                if (gc.ColumnType == typeof(DateTime))
                    gc.DisplayFormat.FormatString = "dd.MM.yyyy HH:mm.ss";
        }

        public void DrillDownGrid(GridView gv, BindingSource bs)
        {
            gv.OptionsClipboard.CopyColumnHeaders = DevExpress.Utils.DefaultBoolean.False;

            gv.GridControl.DataSource = bs;

            gv.SelectionChanged -= gridview_SelectionChanged;
            gv.SelectionChanged += gridview_SelectionChanged;

            foreach (DevExpress.XtraGrid.Columns.GridColumn col in gv.Columns)
                MapGridColumn(col);

            gv.OptionsNavigation.UseOfficePageNavigation = true;
            gv.OptionsSelection.MultiSelect = true;
            gv.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
            gv.OptionsView.ColumnAutoWidth = false;
            gv.OptionsView.ShowAutoFilterRow = true;
            gv.OptionsView.ShowDetailButtons = false;
            gv.OptionsView.ShowGroupPanel = false;
            gv.BestFitMaxRowCount = 50;
            gv.BestFitColumns();
        }
        #endregion

        #region Product Photo Releated

        void XForm_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle > -1)
                if ((e.Column.FieldName == "Scan" || e.Column.FieldName == "ScA" || e.Column.FieldName == "PhotoMikro") &&
                    (e.CellValue == DBNull.Value || e.CellValue == null))
                {
                    //e.DisplayText = "X";
                    e.Graphics.DrawImageUnscaled(notready, e.Bounds.X + (e.Bounds.Width / 2 - 16), e.Bounds.Y);
                    e.Handled = true;
                }
        }



        void gridview_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            GridView view = sender as GridView;

            if (e.RowHandle > -1)
            {
                if (e.Column.FieldName == "Scan")
                {
                    int productId = GetProductId(view, e.RowHandle);
                    if (productId > 0)
                        Goster(productId);
                }
                else if (e.Column.FieldName == "ScA")
                {
                    int aksesuarId = GetAksesuarId(view, e.RowHandle);
                    if (aksesuarId > 0)
                        GosterA(aksesuarId);

                }
            }
        }

        private int GetProductId(GridView gv, int rowHandle)
        {
            if (gv.GetDataRow(rowHandle) != null)
                if (gv.GetDataRow(rowHandle)["ProductId"] != null)
                    return gv.GetDataRow(rowHandle)["ProductId"].ToInt(-1);

            return -1;
        }

        private int GetAksesuarId(GridView gv, int rowHandle)
        {
            int aksesuarId = gv.GetDataRow(rowHandle)["AksesuarId"].ToInt(-1);
            return aksesuarId;
        }

        public List<string> ClickableColumns = new List<string>();
        void gridview_MouseMove(object sender, MouseEventArgs e)
        {
            GridView view = sender as GridView;
            GridHitInfo info = view.CalcHitInfo(new Point(e.X, e.Y));

            if (info.InRowCell && info.Column.FieldName == "Scan" && info.RowHandle > -1)
            {
                int productId = GetProductId(view, info.RowHandle);
                if (productId > 0)
                    view.GridControl.Cursor = Cursors.Hand;
            }
            else if (info.InRowCell && info.Column.FieldName == "ScA" && info.RowHandle > -1)
            {
                int aksesuarId = GetAksesuarId(view, info.RowHandle);
                if (aksesuarId > 0)
                    view.GridControl.Cursor = Cursors.Hand;
            }
            else if (info.InRowCell && ClickableColumns.Contains(info.Column.FieldName))
            {
                if (view.GetRowCellDisplayText(info.RowHandle, info.Column).ToStr() != "")
                    view.GridControl.Cursor = Cursors.Hand;

            }
            else
                view.GridControl.Cursor = Cursors.Default;
        }

        public void gridview_CalcRowHeight(object sender, RowHeightEventArgs e)
        {
            if (e.RowHandle > -1)
                if (e.RowHeight < notready.Height)
                    e.RowHeight = notready.Height;
        }



        public void Goster(int ProductId)
        {
            GosterBase(ProductId);
        }

        public void GosterA(int AksesuarId)
        {
            GosterBaseA(AksesuarId);
        }

        private static void GosterBase(int ProductId)
        {
            if (ProductId > 0)
            {
                //Notify("Please wait while fetching fabric image...");
                Cursor.Current = Cursors.WaitCursor;

                using (Entities.DetailView dv = new Entities.DetailView(ProductId))
                    dv.ShowDialog();

                GC.Collect();

                Cursor.Current = Cursors.Default;
            }
        }

        private static void GosterBaseA(int AksesuarId)
        {
            //if (AksesuarId > 0)
            //{
            //    //Notify("Please wait while fetching fabric image...");
            //    Cursor.Current = Cursors.WaitCursor;

            //    using (DetailA dv = new DetailA(AksesuarId))
            //        dv.ShowDialog();

            //    GC.Collect();

            //    Cursor.Current = Cursors.Default;
            //}
        }

        public static void ShowProductPhoto(int ProductId)
        {
            GosterBase(ProductId);
        }

        public static void ShowAksesuarPhoto(int AksesuarId)
        {
            GosterBaseA(AksesuarId);
        }


        #endregion

        #region Repository Helpers

        public RepositoryItem RI(Rp repository)
        {
            return RepositoryManager.Get(repository);
        }

        public RepositoryItem RI(int repository)
        {
            return RepositoryManager.Get(repository);
        }

        public RepositoryItemGridLookUpEdit GetIntellisensedRI(DataTable dataSource)
        {
            return GetCustomGLE(dataSource, "Name", "Name");
        }

        public RepositoryItemGridLookUpEdit GetNebimRI(DataTable dataSource, string ValueMember)
        {
            return RepositoryManager.GetGLESablon(dataSource, "sAciklama", ValueMember);
        }

        public RepositoryItemGridLookUpEdit GetCustomGLE(DataTable dt, string displayMember, string valueMember)
        {
            RepositoryItemGridLookUpEdit ri = RepositoryManager.GetGLESablon(dt, displayMember, valueMember);

            // ri.View.Columns.Clear();

            int visibleindex = 0;
            foreach (DataColumn column in dt.Columns)
            {
                string caption = column.Caption;
                if (caption != "UserId" && caption != "TS" && caption != "Deleted" && caption != "ModifiedOn")
                {
                    //GridColumn col = ri.View.Columns.AddField(caption);
                    GridColumn col = ri.View.Columns[caption];

                    if ((col.FieldName != valueMember && col.FieldName != displayMember || col.FieldName == "UreticiId") && !(dt.TableName == "ProductCategory" && col.FieldName == "BrandId"))
                        MapGridColumn(col);

                    col.VisibleIndex = visibleindex++;
                    col.Caption = caption;
                }
            }

            return ri;
        }

        public RepositoryItemGridLookUpEdit GetCustomRI(string caption, bool createRuntimeID, params string[] items)
        {
            string valueMember = caption;

            DataTable dataSource = new DataTable();

            dataSource.Columns.Add("Id", typeof(int));
            dataSource.Columns.Add(caption, typeof(string));

            for (int i = 0; i < items.Length; i++)
                dataSource.Rows.Add(new object[] { i + 1, items[i] });

            if (createRuntimeID)
                valueMember = "Id";
            else
                dataSource.Columns.RemoveAt(0);

            return RepositoryManager.GetGLESablon(dataSource, caption, valueMember);
        }

        #endregion



        #region Database Helpers

        public void GetDetails(string SemiColonSeperatedTableNames, string SP, params object[] prm)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                MyData dsNew = (MyData)Session.DataManager.Fill(new MyData(), SemiColonSeperatedTableNames, SP, prm);

                ds.Merge(dsNew, false, MissingSchemaAction.AddWithKey);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        #endregion


        #region KST Releated

        public void gv2_CellMerge(object sender, CellMergeEventArgs e)
        {
            GridView view = sender as GridView;
            e.Merge = view.GetRowCellDisplayText(e.RowHandle1, e.Column) == view.GetRowCellDisplayText(e.RowHandle2, e.Column) &&
                !e.Column.Caption.Contains("Mt") &&
                view.GetRowCellDisplayText(e.RowHandle1, "SipNo2") == view.GetRowCellDisplayText(e.RowHandle2, "SipNo2");
            e.Handled = true;
        }
        #endregion

    }
}